/* Layout */
import Layout from '@/layout'
import { constantRoutes } from '@/router'
import { getRouters } from '@/api/menu'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

// 处理路由组件，以便页面能够识别
export function handleAsyncRouter(routes) {
  routes.forEach(route => {
    // Layout ParentView 组件特殊处理
    if (route.component === 'Layout') {
      route.component = Layout
    } else {
      route.component = loadView(route.component)
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = handleAsyncRouter(route.children)
    } else {
      delete route['children']
      delete route['redirect']
    }
  })
  return routes
}

export const loadView = (view) => {
  if (process.env.NODE_ENV === 'development') {
    return (resolve) => require([`@/views/${view}`], resolve)
  } else {
    // 使用 import 实现生产环境的路由懒加载
    return () => import(`@/views/${view}`)
  }
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }) {
    // 除了默认的路由资源，其他的全部根据用户的权限从后端加载，所以这里就不需要根据用户的role进行判断过滤
    return new Promise(resolve => {
      getRouters().then(res => {
        const accessedRoutes = handleAsyncRouter(res.data)
        accessedRoutes.push({ path: '*', redirect: '/404', hidden: true })
        // 所以这里就不需要根据用户的role进行判断过滤，因为返回的都是具有权限的
        commit('SET_ROUTES', accessedRoutes)

        resolve(accessedRoutes)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
